package sv.com.seguros.web.controller.asg;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import sv.com.seguros.dto.asg.AsgAbono;
import sv.com.seguros.dto.asg.AsgPoliza;
import sv.com.seguros.dto.sgd.SgdUsuario;
import sv.com.seguros.exception.WebException;
import sv.com.seguros.web.controller.BaseController;
import sv.com.seguros.web.util.DBContext;
import sv.com.seguros.web.util.WebUtilidades;

@Controller
@RequestMapping("/polizas")
public class AsgPolizaController extends BaseController {

	private static final long serialVersionUID = 3834669882649782965L;
	
	@RequestMapping(value = "/save", method = {RequestMethod.GET, RequestMethod.POST})
	public void save(Model model, HttpServletResponse response,
			@ModelAttribute AsgPoliza asgPoliza) {
		Map<String, Object> result = new HashMap<String, Object>();
		asgPoliza.setAsgPolizaFechaCreacion(WebUtilidades.dateFormatAsYYYYMMDDHHMMSS.format(new Date()));
		asgPoliza.setSgdUsuario(new SgdUsuario(WebUtilidades.getSgdUsuarioIdFromAcegi()));
		try {
			DBContext.getAsgPolizaService().createPoliza(asgPoliza);
			result.put("asgPolizaId", asgPoliza.getAsgPolizaId());
			result.put("data", JSONArray.fromObject(DBContext.getAsgPolizaDao().findAllByAsgClienteId(asgPoliza.getAsgCliente().getAsgClienteId())));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/findAsgAbonosByAsgPolizaId", method = {RequestMethod.GET, RequestMethod.POST})
	public void findAsgAbonosByAsgPolizaId(@RequestParam Long asgPolizaId, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result.put("data", JSONArray.fromObject(DBContext.getAsgAbonoDao().findAllByAsgPolizaId(asgPolizaId)));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/deleteAbono", method = {RequestMethod.GET, RequestMethod.POST})
	public void deleteAbono(@RequestParam Long asgPolizaId, @RequestParam Long asgAbonoId, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			AsgPoliza asgPoliza = (AsgPoliza) DBContext.getBaseDao().findById(AsgPoliza.class, asgPolizaId);
			if(asgPoliza == null) throw new WebException("Poliza no encontrada");
			DBContext.getAsgPolizaService().deleteAbono(asgPoliza, asgAbonoId);
			result.put("data", JSONArray.fromObject(DBContext.getAsgAbonoDao().findAllByAsgPolizaId(asgPolizaId)));
			result.put("cantidadCuotas", asgPoliza.getAsgPolizaCantidadCuota());
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/updateAbonos", method = {RequestMethod.GET, RequestMethod.POST})
	public void udpateAbonos(@RequestParam Long asgPolizaId, 
			@RequestParam String jsonString, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			AsgPoliza asgPoliza = (AsgPoliza) DBContext.getBaseDao().findById(AsgPoliza.class, asgPolizaId);
			if(asgPoliza == null) throw new WebException("Poliza no encontrada");
			if(StringUtils.isNotBlank(jsonString) && !"[]".equals(jsonString)){
				List<AsgAbono> asgAbonos = (List<AsgAbono>) JSONArray.toCollection(JSONArray.fromObject(jsonString), AsgAbono.class);
				DBContext.getAsgPolizaService().updateAbonos(asgAbonos, asgPoliza);
			}
			result.put("data", JSONArray.fromObject(DBContext.getAsgAbonoDao().findAllByAsgPolizaId(asgPolizaId)));
			result.put("cantidadCuotas", asgPoliza.getAsgPolizaCantidadCuota());
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/deletePoliza", method = {RequestMethod.GET, RequestMethod.POST})
	public void deletePoliza(@RequestParam Long asgPolizaId, HttpServletResponse response, @RequestParam Long asgClienteId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DBContext.getAsgPolizaService().deleteAsgPoliza(asgPolizaId);
			result.put("data", JSONArray.fromObject(DBContext.getAsgPolizaDao().findAllByAsgClienteId(asgClienteId)));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception: ", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}	

}
